/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';

class KeyboardDetector extends StatefulWidget {
  const KeyboardDetector({
    super.key,
    required this.child,
    required this.onControlPress,
    required this.onShiftPress,
  });

  final Widget child;

  final Function(bool isPressed, int pressedKeysLength) onControlPress;
  final Function(bool isPressed, int pressedKeysLength) onShiftPress;

  @override
  KeyboardDetectorState createState() {
    return KeyboardDetectorState();
  }
}

class KeyboardDetectorState extends State<KeyboardDetector> {
  final Set<LogicalKeyboardKey> _pressedKeys = {};

  @override
  Widget build(BuildContext context) {
    return RawKeyboardListener(
      focusNode: FocusNode(),
      autofocus: true,
      onKey: (RawKeyEvent event) {
        if (event is RawKeyDownEvent) {
          _pressedKeys.add(event.logicalKey);
          // 本组件所有手势，键盘不允许同时按下两个键
          if (_pressedKeys.length > 1) return;

          if (event.logicalKey == LogicalKeyboardKey.controlLeft ||
              event.logicalKey == LogicalKeyboardKey.controlRight) {
            widget.onControlPress(true, _pressedKeys.length);
          } else if (event.logicalKey == LogicalKeyboardKey.shiftLeft ||
              event.logicalKey == LogicalKeyboardKey.shiftRight) {
            widget.onShiftPress(true, _pressedKeys.length);
          }
        } else if (event is RawKeyUpEvent) {
          _pressedKeys.remove(event.logicalKey);
          // 本组件所有手势，键盘不允许同时按下两个键
          if (_pressedKeys.isNotEmpty) return;

          if (event.logicalKey == LogicalKeyboardKey.controlLeft ||
              event.logicalKey == LogicalKeyboardKey.controlRight) {
            widget.onControlPress(false, _pressedKeys.length);
          } else if (event.logicalKey == LogicalKeyboardKey.shiftLeft ||
              event.logicalKey == LogicalKeyboardKey.shiftRight) {
            widget.onShiftPress(false, _pressedKeys.length);
          }
        }
      },
      child: widget.child,
    );
  }
}
